package com.twan.kotlinbase.util

import android.content.Context
import com.blankj.utilcode.util.SPUtils
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * 用法 var aInt: Int by SPDelegate<Int>("aInt", 0)
 * 赋值:  aInt = 9
 */
class SPDelegate<T>(val key:String,val default:T):ReadWriteProperty<Any,T> {

    val prefs by lazy {
        SPUtils.getInstance()
    }

    override fun getValue(thisRef: Any, property: KProperty<*>): T {
        return findPreference(key, default)
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
        putPreference(key, value)
    }

    private fun <K> findPreference(name:String, default: K):K = with(prefs) {
        val res: Any = when(default) {
            is Long -> getLong(name, default)
            is String -> getString(name, default)
            is Int -> getInt(name, default)
            is Boolean -> getBoolean(name, default)
            is Float -> getFloat(name, default)
            else -> throw IllegalAccessException("This type can be saved into Preferences")
        }
        res as K
    }

    private fun <U> putPreference(name: String, value: U) = with(prefs) {
        when(value) {
            is Long -> put(name, value)
            is String -> put(name, value)
            is Int -> put(name, value)
            is Boolean -> put(name, value)
            is Float -> put(name, value)
            else -> throw IllegalAccessException("This type can be saved into Preferences")
        }
    }

}